#include "routelistform.h"
#include "ui_routelistform.h"

RouteListForm::RouteListForm(Geocaching *aProg, QWidget *parent) :
    QWidget(parent), ui(new Ui::RouteListForm), myProg(aProg)
{
    ui->setupUi(this);
    setFixedSize(size());
    connect(myProg, SIGNAL(RouteAdded(Route)), this, SLOT(UpdateForm()));
    connect(myProg, SIGNAL(RouteDeleted(ulong)), this, SLOT(UpdateForm()));
    connect(myProg, SIGNAL(RouteEdited(Route)), this, SLOT(UpdateForm()));
    connect(myProg, SIGNAL(CurrentRouteChanged()), this, SLOT(UpdateForm()));
}

RouteListForm::~RouteListForm()
{
    if(ui)  delete ui;
}

void RouteListForm::activateWindow()
{
    UpdateForm();
}

void RouteListForm::UpdateForm(void)
{
    ui->routeListWidget->clear();
    ui->propertyListWidget->clear();
    QList <Route> formRouteList = myProg->GetRouteList();
    foreach(Route tmpRoute, formRouteList)
    {
        QListWidgetItem *item = new QListWidgetItem(tmpRoute.GetName(), ui->routeListWidget);
        item->setData(Qt::UserRole, static_cast<qulonglong>(tmpRoute.GetID()));
        item->setText(tmpRoute.GetName());
        if(tmpRoute.GetID() == myProg->GetCurrentRouteID()) item->setTextColor(Qt::darkRed);
        else                                                item->setTextColor(Qt::black);
    }
    QListWidgetItem *item = ui->routeListWidget->currentItem();
    if(!item)
    {
        ui->editRouteButton->setEnabled(false);
        ui->deleteRouteButton->setEnabled(false);
        ui->viewSelectedButton->setEnabled(false);
    }
    else
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        ui->editRouteButton->setEnabled(tmpID);
        ui->deleteRouteButton->setEnabled(tmpID);
        ui->viewSelectedButton->setEnabled(tmpID != myProg->GetCurrentRouteID());
    }
}

void RouteListForm::on_addRouteButton_clicked()
{
    AddRouteDialog arDialog(myProg->GetPointList());
    arDialog.setWindowFlags(arDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
    if(arDialog.exec())
    {
        Route tmpRoute;
        bool setCurrent = false;
        if(arDialog.Result(&tmpRoute, setCurrent))
            myProg->AddRoute(&tmpRoute, setCurrent);
    }
}

void RouteListForm::on_editRouteButton_clicked()
{
    QListWidgetItem *item = ui->routeListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        Route tmpRoute;
        if(myProg->GetRoute(tmpID, &tmpRoute))
        {
            EditRouteDialog erDialog(&tmpRoute, myProg->GetPointList(), tmpID == myProg->GetCurrentRouteID());
            erDialog.setWindowFlags(erDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
            if(erDialog.exec())
            {
                bool setCurrent = false;
                if(erDialog.Result(setCurrent))
                    myProg->EditRoute(tmpID, &tmpRoute, setCurrent);
            }
        }
    }
}

void RouteListForm::on_deleteRouteButton_clicked()
{
    QListWidgetItem *item = ui->routeListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        myProg->DeleteRoute(tmpID);
    }
}

void RouteListForm::on_routeListWidget_doubleClicked(const QModelIndex& /*index*/)
{
    ui->propertyListWidget->clear();
    QListWidgetItem *item = ui->routeListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        Route tmpRoute;
        if(myProg->GetRoute(tmpID, &tmpRoute))
        {
            QString tmpString;
            unsigned long N = tmpRoute.GetPointCount();
            QListWidgetItem *itemProperty = new QListWidgetItem(tmpRoute.GetName(), ui->propertyListWidget);
            if(N > 0)   tmpString.sprintf("Список точек маршрута.");
            else        tmpString.sprintf("В маршруте нет точек.");
            itemProperty = new QListWidgetItem(tmpString, ui->propertyListWidget);
            Point tmpPoint;
            for(unsigned long i = 0; i < N; ++i)
            {
                unsigned long tmpID = tmpRoute.GetPoint(i);
                QListWidgetItem *itemPoint = new QListWidgetItem(tmpPoint.GetName(), ui->propertyListWidget);
                itemPoint->setData(Qt::UserRole, static_cast<int>(tmpRoute.GetPoint(i)));
                myProg->GetPoint(tmpID, &tmpPoint);
                itemPoint->setText(tmpPoint.GetName());
            }
            N = tmpRoute.GetFileCount();
            if(N > 0)   tmpString.sprintf("Список привязанных файлов.");
            else        tmpString.sprintf("Нет привязанных файлов.");
            itemProperty = new QListWidgetItem(tmpString, ui->propertyListWidget);
            for(unsigned long i = 0; i < N; ++i)
            {
                QListWidgetItem *itemFile = new QListWidgetItem(tmpRoute.GetFileName(i), ui->propertyListWidget);
                itemFile->setData(Qt::UserRole, tmpRoute.GetFileName(i));
                itemFile->setWhatsThis("FILE");
            }
        }
    }
}

void RouteListForm::on_routeFindLineEdit_returnPressed()
{
    if(!ui->routeFindLineEdit->text().isEmpty())
    {
        unsigned long findStartNumber = ui->routeListWidget->currentRow(), N = ui->routeListWidget->count();
        for(unsigned long i = ++findStartNumber; i < N; ++i)
        {
            QString tmpString = ui->routeListWidget->item(i)->text();
            tmpString.resize(ui->routeFindLineEdit->text().size());
            if(!tmpString.compare(ui->routeFindLineEdit->text()))
            {
                ui->routeListWidget->setCurrentRow(i);
                return;
            }
        }
        for(unsigned long i = 0; i < findStartNumber; ++i)
        {
            QString tmpString = ui->routeListWidget->item(i)->text();
            tmpString.resize(ui->routeFindLineEdit->text().size());
            if(!tmpString.compare(ui->routeFindLineEdit->text()))
            {
                ui->routeListWidget->setCurrentRow(i);
                return;
            }
        }
    }
}

void RouteListForm::on_viewSelectedButton_clicked()
{
    QListWidgetItem *item = ui->routeListWidget->currentItem();
    if(item)
    {
        myProg->SetCurrentRoute(item->data(Qt::UserRole).toULongLong());
        ui->hideSelectedButton->setEnabled(true);
    }
}

void RouteListForm::on_hideSelectedButton_clicked()
{
    myProg->SetCurrentRoute(0);
    ui->hideSelectedButton->setEnabled(false);
}

void RouteListForm::on_propertyListWidget_doubleClicked(const QModelIndex& /*index*/)
{
    QListWidgetItem *item = ui->propertyListWidget->currentItem();
    if(item && (item->whatsThis() == "FILE"))
    {
        QString file_name = item->data(Qt::UserRole).toString();
        file_name = QDir::cleanPath(file_name);
        if(!QFile::exists(file_name))
        {
            QMessageBox::warning(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Файл не существует!");
            return;
        }
        if(!QDesktopServices::openUrl(QUrl(QUrl::fromLocalFile(file_name))))
        {
            QMessageBox::information(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Не найдена программа для его открытия!");
            return;
        }
    }
}

void RouteListForm::on_routeListWidget_currentRowChanged(int currentRow)
{
    ui->propertyListWidget->clear();
    if(currentRow == -1)
    {
        ui->editRouteButton->setEnabled(false);
        ui->deleteRouteButton->setEnabled(false);
        ui->viewSelectedButton->setEnabled(false);
    }
    else
    {
        QListWidgetItem *item = ui->routeListWidget->currentItem();
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        ui->editRouteButton->setEnabled(tmpID);
        ui->deleteRouteButton->setEnabled(tmpID);
        ui->viewSelectedButton->setEnabled(tmpID != myProg->GetCurrentRouteID());
    }
}
